package com.liaoyin.travel.util;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class AES256EncryptionUtil {


	public static boolean initialized = false;

	public static final String ALGORITHM = "AES";

	/**
	 * @param str String   要被加密的字符串
	 * @param key String   加/解密要用的长度为32的字符串（256位字节）密钥
	 * @return String  加密后的字符串
	 */
	public static String Aes256Encode(String str, String key) {
		initialize();
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES"); //生成加密解密需要的Key
			cipher.init(Cipher.ENCRYPT_MODE, keySpec);
			byte[] bytes = cipher.doFinal(str.getBytes("UTF-8"));
			result = new BASE64Encoder().encode(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * @param content String   要被解密的字符串
	 * @param key     String     加/解密要用的长度为32的字符串（256位字节）密钥
	 * @return String  解密后的字符串
	 */
	public static String Aes256Decode(String content, String key) {
		initialize();
		String result = null;
		try {
			Cipher cipher = Cipher.getInstance(ALGORITHM, "BC");
			SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "AES"); //生成加密解密需要的Key
			cipher.init(Cipher.DECRYPT_MODE, keySpec);
			byte[] bytes = new BASE64Decoder().decodeBuffer(content);
			byte[] decoded = cipher.doFinal(bytes);
			result = new String(decoded, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static void initialize() {
		if (initialized) {
            return;
        }
		Security.addProvider(new BouncyCastleProvider());
		initialized = true;
	}

}
